package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.AllyActivateRewardStatusEnum;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.AllyActivateReward20;
import com.yourenbang.lingyun.domain.AllyActivateReward20Example;
import com.yourenbang.lingyun.domain.UserBase;
import com.yourenbang.lingyun.mapper.AllyActivateReward20Mapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.mapper.UserBaseMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.MigrateDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.AppUserActivate;
import com.yourenbang.lingyun.transaction.web.service.migrate.AllyActivateRewardMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service("allyActivateRewardMigrateService")
public class AllyActivateRewardMigrateServiceImpl extends AbstractMigrateService implements AllyActivateRewardMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private AllyActivateReward20Mapper allyActivateReward20Mapper;

    /**
     * 激活返现
     */
    @Override
    public void userActivate(MigrateDTO dto) {
        if (StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_INSERT)) {
            allyActivateRewardInsert(dto);
        } else if (StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_UPDATE)) {
            allyActivateRewardUpdate(dto);
        } else if (StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_DELETE)) {
            allyActivateRewardDelete(dto);
        } else if (StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_UPDATE_ACTIVITY)) {
            allyCallActivateRewardUpdate(dto);
        } else {
            KLog.error("[商户-考拉快收-数据同步]激活返现,不支持的数据操作入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
        }
    }

    /**
     * 激活返现插入
     * 必须参数：ProductType，from_user_id，to_user_id, type
     */
    private void allyActivateRewardInsert(MigrateDTO dto) {

        AppUserActivate userActivate = JSONObject.parseObject(dto.getData(), AppUserActivate.class);
        if (userActivate == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现插入,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(userActivate.getFromUserId(), userActivate.getToUserId(), userActivate.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]激活返现插入,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        UserBase fromUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getFromUserId(), redis);
        if (fromUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现插入,未获取到凌云用户fromUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户fromUserBase");
        }

        UserBase toUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getToUserId(), redis);
        if (toUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现插入,未获取到凌云用户toUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户toUserBase");
        }

        AllyActivateReward20Example reward20Example = new AllyActivateReward20Example();
        reward20Example.createCriteria()
                .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                .andToUserBaseIdEqualTo(toUserBase.getUserBaseId())
                .andTypeEqualTo(userActivate.getType())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userActivate.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<AllyActivateReward20> allyActivateRewardList = allyActivateReward20Mapper.selectByExample(reward20Example);
        if (!CollectionUtils.isEmpty(allyActivateRewardList)) {
            KLog.warn("[商户-考拉快收-数据同步]激活返现插入,已存在该数据数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "已存在该数据");
        }

        AllyActivateReward20 activateReward = fmtAllyActivateReward20Data(userActivate, fromUserBase, toUserBase);

        //状态为0插入解冻时间
        if (userActivate.getStatus() != null) {
            if (userActivate.getStatus() == 0) {
                activateReward.setFreezeResultTime(LocalDateTime.now());
            } else if (userActivate.getStatus() == 10) {
                activateReward.setFreezeBeginTime(LocalDateTime.now());
            }
        }

        int inCount = allyActivateReward20Mapper.insertSelective(activateReward);
        BizAssertUtils.assertOne(inCount, "添加激活返现失败");
    }

    /**
     * 激活返现更新
     * 必须参数：ProductType，from_user_id，to_user_id, type
     */
    private void allyActivateRewardUpdate(MigrateDTO dto) {

        AppUserActivate userActivate = JSONObject.parseObject(dto.getData(), AppUserActivate.class);
        if (userActivate == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现更新,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(userActivate.getFromUserId(), userActivate.getToUserId(), userActivate.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]激活返现更新,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        UserBase fromUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getFromUserId(), redis);
        if (fromUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现更新,未获取到凌云用户fromUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户fromUserBase");
        }

        UserBase toUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getToUserId(), redis);
        if (toUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]激活返现更新,未获取到凌云用户toUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户toUserBase");
        }

        AllyActivateReward20Example reward20Example = new AllyActivateReward20Example();
        reward20Example.createCriteria()
                .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                .andToRoleEqualTo(userActivate.getToRoleId())
                .andTypeEqualTo(userActivate.getType())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userActivate.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<AllyActivateReward20> allyActivateRewardList = allyActivateReward20Mapper.selectByExample(reward20Example);
        if (CollectionUtils.isEmpty(allyActivateRewardList)) {
            if (StringUtils.equalsAny(userActivate.getProductType(), "05", "08")) {
                AllyActivateReward20Example epoaReward20Example = new AllyActivateReward20Example();
                if (StringUtils.equals(userActivate.getProductType(), "05")) {
                    epoaReward20Example.createCriteria()
                            .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                            .andToRoleEqualTo(userActivate.getToRoleId())
                            .andTypeEqualTo(userActivate.getType())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(userActivate.getProductType(), "08")) {
                    epoaReward20Example.createCriteria()
                            .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                            .andTypeEqualTo(userActivate.getType())
                            .andToRoleEqualTo(userActivate.getToRoleId())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                allyActivateRewardList = allyActivateReward20Mapper.selectByExample(epoaReward20Example);
            }
        }

        if (CollectionUtils.isEmpty(allyActivateRewardList)) {
            KLog.error("[商户-考拉快收-数据同步]激活返现更新,未找到原激活返现数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原激活返现数据");
        }
        AllyActivateReward20 oldReward = allyActivateRewardList.get(0);
        AllyActivateReward20 activateReward = fmtAllyActivateReward20Data(userActivate, fromUserBase, toUserBase);
        activateReward.setAllyActivateRewardId(oldReward.getAllyActivateRewardId());

        if (oldReward.getStatus() != null && userActivate.getStatus() != null) {
            if (oldReward.getFreezeBeginTime() == null && oldReward.getStatus() == 40 && userActivate.getStatus() == 10) {
                activateReward.setFreezeBeginTime(LocalDateTime.now());
            }
            if (oldReward.getFreezeResultTime() == null && oldReward.getStatus() == 10 && (userActivate.getStatus() == 20 || userActivate.getStatus() == 30)) {
                activateReward.setFreezeResultTime(LocalDateTime.now());
            }
        }

        int upCount = allyActivateReward20Mapper.updateByPrimaryKeySelective(activateReward);
        BizAssertUtils.assertOne(upCount, "更新激活返现失败");
    }

    /**
     * 机具回调激活返现更新
     * 必须参数：ProductType，from_user_id，to_user_id, type
     */
    private void allyCallActivateRewardUpdate(MigrateDTO dto) {

        AppUserActivate userActivate = JSONObject.parseObject(dto.getData(), AppUserActivate.class);
        if (userActivate == null) {
            KLog.error("[商户-考拉快收-数据同步]机具回调,激活返现更新,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(userActivate.getFromUserId(), userActivate.getToUserId(), userActivate.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]机具回调,激活返现更新,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        UserBase fromUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getFromUserId(), redis);
        if (fromUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]机具回调,激活返现更新,未获取到凌云用户fromUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户fromUserBase");
        }

        UserBase toUserBase = getUserBase(userBaseMapper, userBaseExtMapper, userActivate.getToUserId(), redis);
        if (toUserBase == null) {
            KLog.error("[商户-考拉快收-数据同步]机具回调,激活返现更新,未获取到凌云用户toUserBase,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户toUserBase");
        }

        AllyActivateReward20Example reward20Example = new AllyActivateReward20Example();
        reward20Example.createCriteria()
                .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                .andTypeEqualTo(userActivate.getType())
                .andToRoleEqualTo(userActivate.getToRoleId())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userActivate.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<AllyActivateReward20> allyActivateRewardList = allyActivateReward20Mapper.selectByExample(reward20Example);
        if (CollectionUtils.isEmpty(allyActivateRewardList)) {
            if (StringUtils.equalsAny(userActivate.getProductType(), "05", "08")) {
                AllyActivateReward20Example epoaReward20Example = new AllyActivateReward20Example();
                if (StringUtils.equals(userActivate.getProductType(), "05")) {
                    epoaReward20Example.createCriteria()
                            .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                            .andTypeEqualTo(userActivate.getType())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(userActivate.getProductType(), "08")) {
                    epoaReward20Example.createCriteria()
                            .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                            .andTypeEqualTo(userActivate.getType())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                allyActivateRewardList = allyActivateReward20Mapper.selectByExample(epoaReward20Example);
            }
        }

        if (CollectionUtils.isEmpty(allyActivateRewardList)) {
            KLog.error("[商户-考拉快收-数据同步]机具回调,激活返现更新,未找到原激活返现数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原激活返现数据");
        }
        AllyActivateReward20 oldReward = allyActivateRewardList.get(0);
        AllyActivateReward20 activateReward = new AllyActivateReward20();
        activateReward.setAllyActivateRewardId(oldReward.getAllyActivateRewardId());
        activateReward.setToUserBaseId(toUserBase.getUserBaseId());
        activateReward.setToUserName(toUserBase.getUserName());
        int upCount = allyActivateReward20Mapper.updateByPrimaryKeySelective(activateReward);
        BizAssertUtils.assertOne(upCount, "机具回调,机具回调更新激活返现失败");
    }

    /**
     * 格式化激活返现数据
     */
    @Override
    public AllyActivateReward20 fmtAllyActivateReward20Data(AppUserActivate userActivate, UserBase fromUserBase, UserBase toUserBase) {
        AllyActivateReward20 activateReward = new AllyActivateReward20();
        activateReward.setFromUserBaseId(fromUserBase.getUserBaseId());
        activateReward.setFromUserName(fromUserBase.getUserName());
        activateReward.setToUserBaseId(toUserBase.getUserBaseId());
        activateReward.setToUserName(toUserBase.getUserName());
        activateReward.setType(StringUtils.isBlank(userActivate.getType()) ? null : userActivate.getType());
        activateReward.setToRole(StringUtils.isBlank(userActivate.getToRoleId()) ? null : userActivate.getToRoleId());
        activateReward.setStatus(getAllyActivateReward20Status(userActivate.getStatus()));
        activateReward.setAmount(userActivate.getAmt());
        activateReward.setFreezeAmount(userActivate.getFreezeAmt());
        activateReward.setAllowanceAmount(userActivate.getAllowanceAmt());
        activateReward.setAllowanceFreezeAmount(userActivate.getAllowanceFreezeAmt());
        activateReward.setMarketStatus(StringUtils.isBlank(userActivate.getMarketStatus()) ?
                null : new Byte(userActivate.getMarketStatus()));
        activateReward.setVersion(userActivate.getVersion());
        activateReward.setChannelId(ChannelIdEnums.convertKuaiShouProductType(userActivate.getProductType()).getCode());
        activateReward.setPlatNo(PlatNoEnums.KLKS.getCode());
        activateReward.setIsDel(Constant.NORMAL);
        activateReward.setCreateTime(userActivate.getCreateTime());
        activateReward.setUpdateTime(userActivate.getUpdateTime() == null ? LocalDateTime.now() :
                userActivate.getUpdateTime());
        return activateReward;
    }

    /**
     * 格式化激活返现状态
     */
    private Short getAllyActivateReward20Status(Integer klksStatus) {
        if (klksStatus == null) {
            return null;
        }
        if (AppUserActivate.status_0.equals(klksStatus)) {
            return AllyActivateRewardStatusEnum.STATUS_0.getCode();
        } else if (AppUserActivate.status_10.equals(klksStatus)) {
            return AllyActivateRewardStatusEnum.STATUS_10.getCode();
        } else if (AppUserActivate.status_20.equals(klksStatus)) {
            return AllyActivateRewardStatusEnum.STATUS_20.getCode();
        } else if (AppUserActivate.status_30.equals(klksStatus)) {
            return AllyActivateRewardStatusEnum.STATUS_30.getCode();
        } else if (AppUserActivate.status_40.equals(klksStatus)) {
            return AllyActivateRewardStatusEnum.STATUS_40.getCode();
        }
        KLog.error("[商户-考拉快收-数据同步]格式化激活返现状态,不支持的激活返现状态,入参:{}", klksStatus);
        throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的通道商户状态");
    }

    /**
     * 激活返现删除
     */
    private void allyActivateRewardDelete(MigrateDTO dto) {
        KLog.error("[商户-考拉快收-数据同步]激活返现删除,不支持的数据操作,入参:{}", dto.toJSON());
        throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
    }

}
